//
//  CXEmotionTools.swift
//  Project03-Weibo-swift
//
//  Created by w on 16/1/28.
//  Copyright © 2016年 w. All rights reserved.
//

import UIKit

let CXEmotionMaxCol = 7
let CXEmotionMaxRow = 3
let CXEmotionMaxCount = CXEmotionMaxRow * CXEmotionMaxCol - 1

/// 提供全部的表情模型；并被包装进了三维数组
class CXEmotionTools: NSObject {

    /// 单例对象
    static let sharedTool = CXEmotionTools()
    
    lazy var emotionBundle: NSBundle = {
        
        let bundlePath = NSBundle.mainBundle().pathForResource("Emoticons", ofType: "bundle")!
        let bundle = NSBundle(path: bundlePath)
        return bundle!
    }()
    /// 归档路径
    private let recentEmoticonPath: String = {
        return (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("CXEmotionRecent.archive")
    }()
    /// 懒加载各表情集合
    lazy var recentEmotions:[CXEmotion] = {
        //解档
        if let recentEmos = NSKeyedUnarchiver.unarchiveObjectWithFile(self.recentEmoticonPath) as? [CXEmotion] {
            return recentEmos
        } else {
            return [CXEmotion]()
        }
    }()
    lazy var defaultEmotions:[CXEmotion] = {
        return self.getEmotions("default/info.plist")
    }()
    lazy var emojiEmotions:[CXEmotion] = {
        return self.getEmotions("emoji/info.plist")
    }()
    lazy var lxhEmotions:[CXEmotion] = {
        return self.getEmotions("lxh/info.plist")
    }()
    
    lazy var allEmotions:[[[CXEmotion]]] = {
        return [
            [self.recentEmotions],  //如果还是作为参数传入分页方法则得到的元素个数为 0
            self.getPagedEmotions(self.defaultEmotions),
            self.getPagedEmotions(self.emojiEmotions),
            self.getPagedEmotions(self.lxhEmotions)
        ]
    }()
}
// MARK: - 提供模型数组
extension CXEmotionTools {
    
    private func getEmotions(pathString:String) -> [CXEmotion]{
        
        let emotionPath = emotionBundle.pathForResource(pathString, ofType: nil)!
        
        let dictArry = NSArray(contentsOfFile: emotionPath)!
        
        //开始for循环 字典转模型
        var tempArry = [CXEmotion]()
        
        for dict in dictArry {
            
            let emotion = CXEmotion(dict: dict as! [String: AnyObject])
            emotion.path = (pathString as NSString).stringByDeletingLastPathComponent //default, emoji, lxh
            tempArry.append(emotion)
        }
        return tempArry
    }
    
    private func getPagedEmotions(emotion: [CXEmotion]) -> [[CXEmotion]] {
        /// 防止个数为 0 的表情也占有一页
        let pageNum = (emotion.count + CXEmotionMaxCount - 1) / CXEmotionMaxCount
        
        var pagedEmotions = [[CXEmotion]]()
        //遍历 分组
        for i in 0..<pageNum {
            
            let location = i * CXEmotionMaxCount
            
            //如果剩余的数量不够 则酌情减少最后一组的元素个数
            let length = (location + CXEmotionMaxCount <= emotion.count) ? CXEmotionMaxCount : emotion.count - location
            let subEmotions = (emotion as NSArray).subarrayWithRange(NSMakeRange(location, length)) as! [CXEmotion]
            pagedEmotions.append(subEmotions)
        }
        return pagedEmotions
    }
}
// MARK: - 保存模型 归档解档 根据
extension CXEmotionTools {
    
    func saveEmotion(emotion: CXEmotion) {
        
        if let index = recentEmotions.indexOf(emotion) { //该方法会调用对象的isEqual方法来比较和筛选
            //发现表情模型已经存在
            recentEmotions.removeAtIndex(index)
        }
        
        recentEmotions.insert(emotion, atIndex: 0)  //添加到数组开头
        //如果数量超过规定的20个 则删除
        while recentEmotions.count > CXEmotionMaxCount {
            recentEmotions.removeLast()
        }
        
        //将数据更新 -> allEmotions
        allEmotions[0][0] = recentEmotions
        
        //将更新的数据归档
        NSKeyedArchiver.archiveRootObject(recentEmotions, toFile: recentEmoticonPath)
    }
    func emotionWithChs(chs: String) -> CXEmotion? {
        
        //找完默认表情 再找lxh表情
//        for emotion in defaultEmotions {
//            if emotion.chs == chs {
//                return emotion
//            }
//        }
//        
//        for emotion in lxhEmotions {
//            if emotion.chs == chs {
//                return emotion
//            }
//        }
//        return nil
        
        //Swift的高阶用法
        if let result = defaultEmotions.filter ({ $0.chs == chs }).last {
            return result
        }
        if let result = lxhEmotions.filter ({ $0.chs == chs }).last {
            return result
        }
        return nil
    }
}